<template>
  <ex-dialog
    width="1000px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    :close-on-click-modal="false"
    @closeDialog="handleClose"
  >
    <div class="main" v-loading="loading">
      <template v-if="pathType == 'add' || pathType == 'edit'">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm" :disabled="disabled">
          <div class="txt">客户信息</div>
          <el-row>
            <el-col :span="18">
              <el-form-item label="客户名称：" prop="clientName">
                <el-input v-model="ruleForm.clientName" placeholder="请填写客户名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="行业类型：" prop="industryType">
                <el-select v-model="ruleForm.industryType" filterable placeholder="请选择" size="small" >
                  <el-option v-for="item in industryList" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="客户地址：" prop="regionAvalue">
                <el-cascader :options="regionOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
                  v-model="ruleForm.regionAvalue" @change="regionChange"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="" prop="address">
                <el-input v-model="ruleForm.address" placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="门店数量：" prop="shopNum">
                <el-input v-model="ruleForm.shopNum" placeholder="请输入门店数量"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="客户对接人：" prop="contactPerson">
                <el-input v-model="ruleForm.contactPerson" placeholder="请输入客户对接人"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="联系方式：" prop="phone">
                <el-input v-model="ruleForm.phone" placeholder="请输入联系方式"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="客户类型：" prop="clientType">

                <el-radio-group v-model="ruleForm.clientType">
                  <el-radio v-for="(item) in clientList" :label="item.id" :key="item.id">{{item.value}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="客户渠道：" prop="source">
                <el-radio-group v-model="ruleForm.source">
                  <el-radio v-for="(item) in sourceList" :label="item.id" :key="item.id">{{item.value}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="ruleForm.source == 2">
            <el-col :span="18">
              <el-form-item label="选择渠道商：" prop="sourceId">
                <el-select v-model="ruleForm.sourceId" filterable placeholder="请选择" size="small" >
                  <el-option v-for="item in sourceIdList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="ruleForm.source == 3">
            <el-col :span="18">
              <el-form-item label="渠道备注：" prop="sourceRemark">
                <el-input type="text" v-model="ruleForm.sourceRemark" autocomplete="off" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="客户级别：" prop="clientLevel">
                <el-radio-group v-model="ruleForm.clientLevel">
                  <el-radio v-for="(item) in levelList" :label="item.id" :key="item.id">{{item.value}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="18">
              <el-form-item label="客户诉求：" prop="appealList">
                <el-checkbox-group v-model="ruleForm.appealList" @change="changeAppealList">
                  <el-checkbox v-for="(item, index) in appealListArray" :key="index"
                    :label="item.id">{{ item.value }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="其他诉求：" prop="otherAppeal" v-if="isOther">
                <el-input type="text" v-model="ruleForm.otherAppeal" autocomplete="off" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="抖音来客账号：" prop="tiktokVisitorAccount">
                <el-input v-model="ruleForm.tiktokVisitorAccount" placeholder="是否注册过抖音来客，有就填写，没有就写待注册"></el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row v-if="pathType =='edit'">
            <el-col :span="18">
              <el-form-item label="运营负责人：" prop="operationManager">
                <el-select v-model="ruleForm.operationManager" filterable placeholder="请选择" size="small" >
                  <el-option v-for="item in operationManagerList" :key="item.id" :label="item.nickName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row> 
          <el-row>
            <el-col :span="18">
              <el-form-item label="客户负责人：" prop="responsiblePerson">
                <el-select v-model="ruleForm.responsiblePerson" filterable placeholder="请选择" size="small" >
                  <el-option v-for="item in responsiblePersonList" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row> 
          <el-row>
            <el-col :span="18">
              <el-form-item label="备注：" prop="">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 8}"
                  placeholder="请输入内容"
                  v-model="ruleForm.remark"
                  maxlength="200"
                  show-word-limit
                  >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>           
        </el-form>
      </template>
    </div>
    <div class="button_box">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        v-if="pathType == 'add' || pathType =='edit'"
        type="primary"
        :loading="AgreeLoading"
        @click="submitForm('ruleForm')"
      >保存提交</el-button>
    </div>
  </ex-dialog>
</template>
<script>
import Loading from "@/components/Loading/index";
// api
import {
  addClient,
  editClient,
  responsibleSelect,
  clientDetail,
  sourceList,
  managerSelect,
} from "@/api/customer/customerFile";
import {
  shopTypeTree,
} from "@/api/merchants";
import {
  getCity
} from "@/api/clientManagement";
export default {
  components: {
    Loading,
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {
    var checkServiceCommission = (rule, value, callback) => {
      //销售原价校验
      let regNumber = /(^[0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
      if(value === ''){
        return callback(new Error("请输入服务佣金"));
      }
      else {
        if(value< 0 || value > 100){
          return callback(new Error("请填写0-100的数值"));
        }else{
          console.log('value',regNumber.test(value))
          if (regNumber.test(value) == false || value === "0.00" || value === "0.0") {
            return callback(new Error("请填写大于0且最多保留两位小数的数值"));
          }else{
            return callback();
          }dd
        }
      }
      
    };
    var checkConsumeCycleRatio = (rule, value, callback) => { //周期消费金额占比校验
      let regNumber = /^\+?[0-9]\d*$/; //大于0的正整数
        if (value === '' ) {
          return callback(new Error('请输入数值'));
        } else if (regNumber.test(value) == false) {
          return callback(new Error('请输入大于等于0的整数'));
        } else {
          return callback()
        }
      };
    var checkShopNum = (rule, value, callback) => { //周期消费金额占比校验
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
        if (value === '' ) {
          return callback(new Error('请输入数值'));
        } else if (regNumber.test(value) == false) {
          return callback(new Error('请输入大于0正整数'));
        } else {
          return callback()
        }
      };
    return {
      labelWidth: "150px",
      inputWidth: "420px",
      title: "创建客户资料",
      loading: false,
      disabled: false,
      AgreeLoading: false,
      ruleForm: {
        id: '',//客户档案id
        clientName: '',//客户名称
        industryType: '',//行业类型 1 餐厅 2 丽人 3 烘培 4 租车 5 商超 6 其他
        province: '',//省
        city: '',//市
        area: '',//区
        address: '',//客户详细地址
        shopNum: '',//门店数量
        contactPerson: '',//客户对接人
        phone: '',//联系方式
        clientType: '',//客户类型 1 渠道运营商 2 大单店商户 3 连锁商户
        clientLevel: '',//客户级别 1.S 2.A 3.B 4.C 5.渠道运营商
        source: '',//客户渠道 
        sourceId: '',//渠道商id
        appealList: [],//客户诉求集合 
        otherAppeal: '',//
        tiktokVisitorAccount: '',//抖音来客账号
        operationManager: '',//运营负责人
        responsiblePerson: '',//客户负责人
        remark: '',//客户备注

        // signTime: '',//签约时间
        // serviceTimeEnd: '',//服务时间结束
        // serviceTimeStart: '',//服务时间开始
        // serviceTypeList: [],//服务类型 bee_client_service_type
        // serviceCommission: null,//服务佣金（单位：百分比）
        // liveNum: null,//直播场次
        // shortVideoNum: null,//短视频数量
        
        date: [],//校验时间用


        regionAvalue: [],//校验地区用
       
      },
      isOther:false,//是否选择其他诉求

      industryList: [],
      clientList: [],
      serviceList: [],
      sourceList:[],
      sourceIdList: [],
      appealListArray: [],//客户诉求列表
      responsiblePersonList: [],
      operationManagerList: [],//运营负责人列表
      regionOptions: [], //城市数组
      responsiblePersonText: '',
      serviceListTxt: '',
      levelList: [
        {id: '1',value: '超头客户 支付GMV ≥ 100万元'},
        {id: '2',value: '头部客户 支付GMV ≥ 50万元'},
        {id: '3',value: '腰部客户 支付GMV ≥ 10万元'},
        {id: '4',value: '尾部客户 支付GMV < 10万元'},
      ],
      cardList: [],//赚卡下拉列表
      rules: {
        clientName: [
          { required: true,message: "请填写客户名称",trigger: ["change", "bulr"]}
        ],
        industryType: [
          { required: true,message: "请选择行业",trigger: ["change" ]}
        ],
        regionAvalue: [
          { required: true,message: "请选择地区",trigger: ["change" ]}
        ],
        address: [
          { required: true,message: "请填写详细地址",trigger: ["change", "bulr"]}
        ],
        shopNum: [
          {  validator: checkShopNum,required: true,trigger: ["change", "bulr"]}
        ],
        contactPerson: [
          { required: true,message: "请输入客户对接人",trigger: ["change", "bulr"]}
        ],
        phone: [
          { required: true,message: "请输入联系方式",trigger: ["change", "bulr"]}
        ],
        clientType: [
          { required: true,message: "请选择客户类型",trigger: ["change" ]}
        ],
        source: [
          { required: true,message: "请选择客户渠道",trigger: ["change" ]}
        ],
        sourceId: [
          { required: true,message: "请选择渠道商",trigger: ["change" ]}
        ],
        sourceRemark: [
          { required: true,message: "请输入渠道备注",trigger: ["change" ]}
        ],
        clientLevel: [
          { required: true,message: "请选择客户级别",trigger: ["change" ]}
        ],
        appealList: [
          { required: true,message: "请选择客户诉求",trigger: ["change" ]}
        ],
        otherAppeal: [
          { required: true,message: "请输入其他诉求",trigger: ["change" ]}
        ],
        tiktokVisitorAccount: [
          { required: true,message: "请输入抖音来客账号",trigger: ["change" ]}
        ],
        signTime: [
          { required: true,message: "请选择日期",trigger: ["change" ]}
        ],
        date: [
          { required: true,message: "请选择服务时间",trigger: ["change" ]}
        ],
        serviceTypeList: [
          { required: true,message: "请选择服务类型",trigger: ["change" ]}
        ],
        serviceCommission: [
          { validator: checkServiceCommission,required: true,trigger: ["change" ]}
        ],
        liveNum: [
          {  validator: checkConsumeCycleRatio,required: true,trigger: ["change" ]}
        ],
        shortVideoNum: [
          {   validator: checkConsumeCycleRatio,required: true,trigger: ["change" ]}
        ],
        operationManager: [
          { required: true,message: "请选择运营负责人",trigger: ["change" ]}
        ],
        responsiblePerson: [
          { required: true,message: "请选择客户负责人",trigger: ["change" ]}
        ],
       
       
      },
    };
  },
  computed: {},
  created() {
    this.getCity()
    this.getresponsiblePersonList()
    this.getoperationManagerList()
    this.getDict()
    this.getSourceList()
    if(this.pathType == 'add'){
      this.title = '创建客户资料'
    }else if(this.pathType == 'edit'){
      this.title = '编辑客户资料'
      this.getDetail()
    }else if(this.pathType == 'look'){
      
      this.title = '查看客户资料'
      this.getDetail()
    }
  },
  mounted() {
   
  },
  computed: {},
  methods: {
    //获取状态字典
    getDict() {
      var dictType = "bee_client_industry_type,bee_client_type,bee_client_service_type,bee_client_source,bee_client_filing_appeal";
      this.$getSelectList(dictType)
        .then((res) => {
          this.industryList = res.result[0].dictList
          this.clientList = res.result[1].dictList
          this.serviceList = res.result[2].dictList
          this.sourceList = res.result[3].dictList
          this.appealListArray = res.result[4].dictList
        })
        .finally(() => {
          this.loading = false;
        });
        console.log('this.industryList',this.industryList)
    },
    // 其他诉求改变
    changeAppealList(){
      this.isOther = this.ruleForm.appealList.find(obj => obj == 5)?true:false
    },
    //客户负责人下拉
    getresponsiblePersonList() {
      responsibleSelect().then((res) => {
          this.responsiblePersonList = res.result
      })
      .finally(() => {
        this.loading = false;
      });
      console.log('this.industryList',this.industryList)
    },
    //运营负责人下拉列表
    
    getoperationManagerList() {
      managerSelect().then((res) => {
          this.operationManagerList = res.result
      })
      .finally(() => {
        this.loading = false;
      });
      console.log('this.industryList',this.industryList)
    },
    //渠道商下拉
    
    getSourceList() {
      sourceList().then((res) => {
          this.sourceIdList = res.result
      })
      .finally(() => {
        this.loading = false;
      });
    },
    getCity() { //查询城市数据
      const params = {};
      getCity(params)
        .then((res) => {
          this.regionOptions = res.result;
          this.regionOptions.forEach((item) => {
            item.children.forEach((items) => {
              items.children.forEach((itemss) => {
                if (itemss.children.length == 0) {
                  itemss.children = null
                }
              })
            })
          })
        })
        .finally(() => { });
    },
    //获取详情
    getDetail(){
      var id = this.id
      clientDetail(id).then(res => {
        
        var data = res.result
        this.ruleForm = {
          ...res.result,
          date: [],
        
        }
        this.ruleForm.regionAvalue = [data.province,data.city,data.area] 
   
        this.isOther = this.ruleForm.appealList.find(obj => obj == 5)?true:false
        console.log('哈哈哈',this.isOther)
      })
    },


    regionChange(value) { //城市区域选择
      this.ruleForm.province = value[0];
      this.ruleForm.city = value[1];
      this.ruleForm.area = value[2];
    },
    //选择时间
    changeTime(e){
      this.ruleForm.serviceTimeStart = e[0]
      this.ruleForm.serviceTimeEnd = e[1]

    },
    
    //取消
    handleClose(formName) {
      this.$emit("update:visible", false);
    },
    submitForm(formName) {
      console.log(this.ruleForm);
      //创建确定
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.AgreeLoading = true
          var data = {
            ...this.ruleForm
          }
          if(!this.isOther){
            data.otherAppeal = ''
          }
          if(this.pathType == 'add'){
            addClient(data).then(res => {
              this.handleClose()
              this.$message.success('创建成功')
              this.$emit('success')
              this.AgreeLoading = false
            }).finally(()=>{
              this.AgreeLoading = false
            })
          }else if(this.pathType == 'edit'){
            editClient(data).then(res => {
              this.handleClose()
              this.$message.success('修改成功')
              this.$emit('success')
              this.AgreeLoading = false
            }).finally(()=>{
              this.AgreeLoading = false
            })
          }
          
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  }
};
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
    padding: 0 !important;
  }

  ::v-deep .ex--dialog--main {
    padding: 10px 20px !important;
  }
}
.el-select,.el-input,.el-cascader{
  width: 400px;
}
.main {
  padding: 20px 20px;
}
.button_box{
  display: flex;
  justify-content: center;
}
.el-radio-group{
  display: flex;
  flex-direction: column;
  .el-radio{
    margin-bottom: 14px;
  }
}
.txt{
  font-size: 20px;
  font-weight: 500;
  color: #333;
  border-bottom: 4px solid #1890ff;
  margin-bottom: 20px;
  padding-bottom: 14px;
}
.listTxt{
  display: flex;
  justify-content: flex-start;
  height: 50px;
  align-items: center;
  .left{
    width: 100px;
  }
}
</style>
